package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.OrderCheck;
import com.lkd.dao.OrderDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.OrderEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.service.OrderService;
import com.lkd.vo.PartnerVO;
import com.lkd.vo.PayVO;
import com.lkd.vo.SkuVO;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Autowired
    private VMService vmService;

    @Autowired
    private UserService userService;

    @Autowired
    private MqttProducer mqttProducer;

    @Override
    public OrderEntity getByOrderNo(String orderNo) {
        QueryWrapper<OrderEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .eq(OrderEntity::getOrderNo,orderNo);
        return this.getOne(qw);
    }

    /**
     * 创建订单
     *
     * @param payVO
     * @return
     */
    @Override
    public OrderEntity createOrder(PayVO payVO) {

        Boolean capacity = vmService.hasCapacity(payVO.getInnerCode(), Long.valueOf(payVO.getSkuId()));
        if(!capacity) throw new LogicException("库存不足");
        OrderEntity orderEntity = new OrderEntity();
        //根据售货机编号查询售货机信息 ,并复制给订单对象
        VmVO vmInfo = vmService.getVMInfo(payVO.getInnerCode());
        BeanUtils.copyProperties(vmInfo, orderEntity);

        orderEntity.setOpenId(payVO.getOpenId());   // 设置openid
        orderEntity.setOrderNo(payVO.getInnerCode()+System.nanoTime()); // 设置订单号
        orderEntity.setPayStatus(VMSystem.PAY_STATUS_NOPAY);   // 设置支付状态为0

        orderEntity.setAddr(vmInfo.getNodeAddr());   // 设置地址

        //通过商品编号查询商品信息，
        SkuVO skuVO = vmService.getSku(payVO.getSkuId());
        BeanUtils.copyProperties(skuVO, orderEntity);
        orderEntity.setAmount(skuVO.getPrice());
        orderEntity.setStatus(VMSystem.ORDER_STATUS_CREATE);

        // 通过userService 获取合作商

        PartnerVO partner = userService.getPartner(vmInfo.getOwnerId());
        BigDecimal bigDecimal = new BigDecimal(skuVO.getRealPrice());
        int bill = bigDecimal.multiply(new BigDecimal(partner.getRatio()))
                .divide(new BigDecimal(100), 0, RoundingMode.HALF_UP).intValue();
        orderEntity.setBill(bill);
        save(orderEntity);



        //将消息放到延迟队列中，10分钟后检查支付状态
        OrderCheck orderCheck = new OrderCheck();
        orderCheck.setOrderNo(orderEntity.getOrderNo());
        try {
            mqttProducer.send("$delayed/600"+ TopicConfig.ORDER_CHECK_TOPIC,2,orderCheck);
        } catch (Exception e) {
            log.error("发送消息失败"+e);
        }


        return orderEntity;
    }


}
